package org.tea.inventory.admin.web.admin;

import com.github.pagehelper.PageInfo;
import org.tea.inventory.admin.annotation.LoginAdmin;
import org.tea.inventory.base.util.ResponseUtil;
import org.tea.inventory.db.domain.AlumniVisitor;
import org.tea.inventory.db.domain.Storage;
import org.tea.inventory.db.service.AlumniRecordStorageService;
import org.tea.inventory.db.service.AlumniVisitorService;
import org.tea.inventory.db.service.StorageService;
import org.tea.inventory.db.util.CharUtil;
import org.tea.inventory.db.util.VisitorUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;	

@RestController
@RequestMapping("/admin/alumniVisitor")
public class AlumniVisitorController {

    @Autowired
    private AlumniVisitorService alumniVisitorService;
    @Autowired
    private StorageService storageService;
    @Autowired
    private AlumniRecordStorageService alumniRecordStorageService;
    /**
     * 查询访客列表
     * @param adminId
     * @param alumniVisitor
     * @param page
     * @param limit
     * @param sort
     * @param order
     * @return
     */
    @GetMapping("/list")
    public Object list(@LoginAdmin Integer adminId,
                       AlumniVisitor alumniVisitor,
                       @RequestParam(value = "page", defaultValue = "1") Integer page,
                       @RequestParam(value = "limit", defaultValue = "10") Integer limit,
                       String sort, String order){
        if(adminId == null){
            return ResponseUtil.fail401();
        }

        PageInfo<AlumniVisitor> pageInfo = alumniVisitorService.queryAlumniVisitor(alumniVisitor, page, limit, sort, order);
        Map<String, Object> data = new HashMap<>();
        data.put("total", pageInfo.getTotal());
        data.put("items", pageInfo.getList());

        return ResponseUtil.ok(data);
    }

    /**
     * 获取指定id的访客详情
     * @param adminId
     * @param id
     * @return
     */
    @GetMapping("read")
    public Object read(@LoginAdmin Integer adminId, Integer id) {
        if(adminId == null) {
            return ResponseUtil.unlogin();
        }
        if(id == null) {
            return  ResponseUtil.badArgumentValue();
        }
        AlumniVisitor visitor = alumniVisitorService.findById(id);
        return ResponseUtil.ok(visitor);
    }

    /**
     * 删除指定id的访客信息
     * @param adminId
     * @param visitor
     * @return
     */
    @PostMapping("delete")
    public Object delete(@LoginAdmin Integer adminId, @RequestBody AlumniVisitor visitor) {
        if(adminId == null) {
            return ResponseUtil.unlogin();
        }
        if(visitor == null) {
            return ResponseUtil.badArgumentValue();
        }
        alumniVisitorService.delete(visitor.getId());
        return ResponseUtil.ok();
    }

    /**
     * 上传访客信息到人脸识别系统
     * @param adminId
     * @param visitor
     * @return
     */
    @PostMapping("upload")
    public Object upload(@LoginAdmin Integer adminId, @RequestBody AlumniVisitor visitor) {
        if(adminId == null) {
            return ResponseUtil.unlogin();
        }
        if(visitor == null) {
            return ResponseUtil.badArgumentValue();
        }
        //获取图片文件下载地址
        String filepath = null;
        if(visitor.getVisitorPhoto() != null){
            Storage storage = alumniRecordStorageService.findByUrl(visitor.getVisitorPhoto());
            filepath = storageService.loadFullFilePath(storage.getFilePath());
        }
        //注册/更新到人员管理
        //1.查询该访客信息是否已经上传到人脸识别系统
        AlumniVisitor vis = new AlumniVisitor();
        vis.setVisitorUserId(visitor.getVisitorUserId());
        vis.setStatus(VisitorUtil.STARTE_FINISH);
        List<AlumniVisitor> list = alumniVisitorService.findAlumniVisitor(vis);
        boolean isExist = false;
        if(list != null && list.size() > 0){
            isExist = true;
            //1-1.存在更新
            System.out.println("已存在 更新update");
            AlumniVisitor v = list.get(0);
            visitor.setPersonId(v.getPersonId());
            visitor.setOriginId(v.getOriginId());
            visitor = VisitorUtil.update(visitor, filepath);
        } else {
            //1-2.不存在添加
            System.out.println("不存在 新建add");
            //人员编号/ID
            String originId = new SimpleDateFormat("yyyyMMddhhmmss").format(new Date());
            visitor.setOriginId(originId + CharUtil.getRandomString(6));
            visitor = VisitorUtil.upload(visitor, filepath);
        }
        alumniVisitorService.uploadVisitor(visitor);
        System.out.println("--------------------");
        //更新访客信息
        //extract_result :
        // 人脸提特征结果：
        // 0-成功；
        // 100-失败，照片上检不到人脸；
        // 200-失败，照片上人脸姿态不正；
        // 300失败，照片上人脸过于模糊；
        // 400-失败，照片上太多人脸；
        // 500-失败，照片格式不符合要求
        String extractResult = visitor.getExtractResult();
        if("-1".equals(extractResult)){
            //失败
            return ResponseUtil.fail(-1,"上传失败");
        } else if ("0".equals(extractResult)){
            int status = VisitorUtil.STARTE_SUBMIT;
            if(isExist){//人员信息已存在，无需添加到权限组
                status = VisitorUtil.STARTE_FINISH;
            } else {
                //添加到权限组
                boolean falg = VisitorUtil.addPermissionGroup(visitor.getPersonId());
                if(falg){
                    status = VisitorUtil.STARTE_FINISH;
                    System.out.println("添加到权限组 成功");
                } else {
                    System.out.println("添加到权限组 失败");
                }
            }
            visitor.setStatus(status);
            //更新访客
            alumniVisitorService.uploadVisitor(visitor);
            return ResponseUtil.ok("上传成功！！！");
        } else if ("100".equals(extractResult)){
            return ResponseUtil.fail(-1,"100-失败，照片上检不到人脸");
        } else if ("200".equals(extractResult)){
            return ResponseUtil.fail(-1,"200-失败，照片上人脸姿态不正");
        } else if ("300".equals(extractResult)){
            return ResponseUtil.fail(-1,"300失败，照片上人脸过于模糊");
        } else if ("400".equals(extractResult)){
            return ResponseUtil.fail(-1,"400-失败，照片上太多人脸");
        } else if ("500".equals(extractResult)){
            return ResponseUtil.fail(-1,"500-失败，照片格式不符合要求");
        } else {
            return ResponseUtil.fail(-1,"上传失败，其他错误");
        }

    }
}
